package club.kingyin.easycache.component.annotation.handler;

import club.kingyin.easycache.component.annotation.EasyCache;
import club.kingyin.easycache.component.handler.MinRandomTimerPostProcess;
import club.kingyin.easycache.component.annotation.Expire;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

// 解析Expire的后置处理器 和EasyCache注解 EasyCache注解优先级最低
@Slf4j
public class AnnotationExpireAutoSetPostProcess extends MinRandomTimerPostProcess {
    @Override
    protected double getCoefficientByMethod(Method method) {
        double factor = 0.7;
        if(method.isAnnotationPresent(EasyCache.class)) {
            EasyCache easyCache = method.getDeclaredAnnotation(EasyCache.class);
            if (easyCache.expire().length > 0) {
                factor = easyCache.expire()[0].factor();
            }
        }
        if (method.isAnnotationPresent(Expire.class)) {
            Expire expire = method.getAnnotation(Expire.class);
            factor = expire.factor();
        }
        return factor;
    }

    @Override
    protected long getTimeByMethod(Method method) {
        long time = 72;
        if(method.isAnnotationPresent(EasyCache.class)) {
            EasyCache easyCache = method.getDeclaredAnnotation(EasyCache.class);
            if (easyCache.expire().length > 0) {
                time = easyCache.expire()[0].time();
            }
        }
        if (method.isAnnotationPresent(Expire.class)) {
            Expire expire = method.getAnnotation(Expire.class);
            time = expire.time();
        }
        return time;
    }

    @Override
    protected TimeUnit getTimeUnitByMethod(Method method) {
        TimeUnit unit = TimeUnit.DAYS;
        if(method.isAnnotationPresent(EasyCache.class)) {
            EasyCache easyCache = method.getDeclaredAnnotation(EasyCache.class);
            if (easyCache.expire().length > 0) {
                unit = easyCache.expire()[0].unit();
            }
        }
        if (method.isAnnotationPresent(Expire.class)) {
            Expire expire = method.getAnnotation(Expire.class);
            unit = expire.unit();
        }
        return unit;
    }

}
